package com.corgi.websocket.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @title: ChatRoomServerEndpoint
 * @description: 聊天室 {@link ServerEndpoint}
 * @author: dengmiao
 * @create: 2019-10-10 09:36
 **/
@Slf4j
@Component
@ServerEndpoint("/chat-room/{username}")
public class ChatRoomServerEndpoint {

	private static final Map<String, Session> LIVING_SESSIONS = new ConcurrentHashMap<>(16);

	@OnOpen
	public void onOpenSession(@PathParam("username") String username,
	                          Session session) {
		String sessionId = session.getId();
		LIVING_SESSIONS.put(sessionId, session);
		// sendMessage(session, "欢迎用户[" + username + "]来到聊天室");
		sendAll("欢迎用户[" + username + "]来到聊天室");
	}

	@OnMessage
	public void onMessage(@PathParam("username") String username,
	                      Session session,
	                      String message) {
		// sendMessage(session, "用户[" + username + "]:" + message);
		sendAll("用户[" + username + "]:" + message);
	}

	@OnClose
	public void onClose(@PathParam("username") String username,
	                    Session session) {
		// 移除当前session
		LIVING_SESSIONS.remove(session.getId());
		// 通知其他人当前session用户离开
		sendAll("用户[" + username + "]离开了聊天室");
	}

	@OnError
	public void onError(Session session,
	                    Throwable t) {
		log.error("当前session{}, 异常{}", session.getId(), t.getMessage());
	}

	/**
	 * 发送全部 广播
	 * @param message
	 */
	private void sendAll(String message) {
		LIVING_SESSIONS.forEach((sessionId, session) -> {
			sendMessage(session, message);
		});
	}

	private void sendMessage(Session session, String message) {
		RemoteEndpoint.Basic basic = session.getBasicRemote();
		try {
			basic.sendText(message);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
